<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['factory:process-template:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['factory:process-template:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="id" label="模板ID，主键" prop="id" min-width="150" align="center" />
        <el-table-column
          key="templateCode"
          label="模板编码，唯一标识"
          prop="templateCode"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="templateName"
          label="模板名称"
          prop="templateName"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="templateDescription"
          label="模板描述"
          prop="templateDescription"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="garmentType"
          label="服装类型：T恤/衬衫/裤子/外套等"
          prop="garmentType"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="styleCategory"
          label="款式分类：男装/女装/童装等"
          prop="styleCategory"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="complexityLevel"
          label="复杂度等级：1-简单，2-中等，3-复杂"
          prop="complexityLevel"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="estimatedTotalTime"
          label="预估总工时（分钟）"
          prop="estimatedTotalTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="estimatedTotalPrice"
          label="预估总工价（元）"
          prop="estimatedTotalPrice"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="isActive"
          label="是否启用：0-停用，1-启用"
          prop="isActive"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="usageCount"
          label="使用次数统计"
          prop="usageCount"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="createBy"
          label="创建人"
          prop="createBy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="updateBy"
          label="更新人"
          prop="updateBy"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="updateTime"
          label="更新时间"
          prop="updateTime"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['factory:process-template:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['factory:process-template:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 工序模板主表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="模板ID，主键" prop="id">
          <el-input v-model="formData.id" placeholder="模板ID，主键" />
        </el-form-item>

        <el-form-item label="模板编码，唯一标识" prop="templateCode">
          <el-input v-model="formData.templateCode" placeholder="模板编码，唯一标识" />
        </el-form-item>

        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="formData.templateName" placeholder="模板名称" />
        </el-form-item>

        <el-form-item label="模板描述" prop="templateDescription">
          <el-input v-model="formData.templateDescription" placeholder="模板描述" />
        </el-form-item>

        <el-form-item label="服装类型：T恤/衬衫/裤子/外套等" prop="garmentType">
          <el-input v-model="formData.garmentType" placeholder="服装类型：T恤/衬衫/裤子/外套等" />
        </el-form-item>

        <el-form-item label="款式分类：男装/女装/童装等" prop="styleCategory">
          <el-input v-model="formData.styleCategory" placeholder="款式分类：男装/女装/童装等" />
        </el-form-item>

        <el-form-item label="复杂度等级：1-简单，2-中等，3-复杂" prop="complexityLevel">
          <el-input
            v-model="formData.complexityLevel"
            placeholder="复杂度等级：1-简单，2-中等，3-复杂"
          />
        </el-form-item>

        <el-form-item label="预估总工时（分钟）" prop="estimatedTotalTime">
          <el-input v-model="formData.estimatedTotalTime" placeholder="预估总工时（分钟）" />
        </el-form-item>

        <el-form-item label="预估总工价（元）" prop="estimatedTotalPrice">
          <el-input v-model="formData.estimatedTotalPrice" placeholder="预估总工价（元）" />
        </el-form-item>

        <el-form-item label="是否启用：0-停用，1-启用" prop="isActive">
          <el-input v-model="formData.isActive" placeholder="是否启用：0-停用，1-启用" />
        </el-form-item>

        <el-form-item label="使用次数统计" prop="usageCount">
          <el-input v-model="formData.usageCount" placeholder="使用次数统计" />
        </el-form-item>

        <el-form-item label="创建人" prop="createBy">
          <el-input v-model="formData.createBy" placeholder="创建人" />
        </el-form-item>

        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="formData.createTime"
            type="datetime"
            placeholder="创建时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="更新人" prop="updateBy">
          <el-input v-model="formData.updateBy" placeholder="更新人" />
        </el-form-item>

        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker
            v-model="formData.updateTime"
            type="datetime"
            placeholder="更新时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ProcessTemplate",
  inheritAttrs: false,
});

import ProcessTemplateAPI, {
  ProcessTemplatePageVO,
  ProcessTemplateForm,
  ProcessTemplatePageQuery,
} from "@/api/factory/process-template";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<ProcessTemplatePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 工序模板主表格数据
const pageData = ref<ProcessTemplatePageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 工序模板主表单数据
const formData = reactive<ProcessTemplateForm>({});

// 工序模板主表单校验规则
const rules = reactive({
  id: [{ required: true, message: "请输入模板ID，主键", trigger: "blur" }],
  templateCode: [{ required: true, message: "请输入模板编码，唯一标识", trigger: "blur" }],
  templateName: [{ required: true, message: "请输入模板名称", trigger: "blur" }],
});

/** 查询工序模板主 */
function handleQuery() {
  loading.value = true;
  ProcessTemplateAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置工序模板主查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开工序模板主弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改工序模板主";
    ProcessTemplateAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增工序模板主";
  }
}

/** 提交工序模板主表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        ProcessTemplateAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ProcessTemplateAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭工序模板主弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除工序模板主 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ProcessTemplateAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
